package ca.ubc.icapture.genapha.actions;

import icapture.AppProperties;
import icapture.SQLMgr;
import icapture.beans.DB.Cohort;
import icapture.beans.DB.Ethnicity;
import icapture.beans.DB.Gene;
import icapture.beans.DB.Phenotypes;
import icapture.beans.DB.SNP;
import icapture.beans.EntrezGeneSummary;
import icapture.beans.PageLink;
import icapture.genapha.GenaphaTools;
import icapture.genapha.GenotypeToolsManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.biomoby.services.ncbi.NCBIServices;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class UpdateKeggPathwayAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) {
        System.out.println("Hi");
        reloadKeggTables();
        System.out.println("Hi2");

        return null;
    }

    public void reloadKeggTables(){

        SQLMgr.deleteKeggGenePathways();
        SQLMgr.deleteKeggGenes();
        SQLMgr.deleteKeggPathways();

        try{
            //ArrayList<String> fileKGContents = Tools.readFile(new URL("ftp://ftp.genome.jp/pub/kegg/genes/organisms/hsa/hsa_ncbi-geneid.list"));
            ArrayList<String> fileKGContents = GenaphaTools.readFile(new URL(AppProperties.get("KeggGeneUrl")));
            //ArrayList<String> fileKGPContents = Tools.readFile(new URL("ftp://ftp.genome.jp/pub/kegg/genes/organisms/hsa/hsa_pathway.list"));
            ArrayList<String> fileKGPContents = GenaphaTools.readFile(new URL(AppProperties.get("KeggGenePathwaysUrl")));
            //ArrayList<String> fileKPContents = Tools.readFile(new URL("ftp://ftp.genome.jp/pub/kegg/pathway/map_title.tab"));
            ArrayList<String> fileKPContents = GenaphaTools.readFile(new URL(AppProperties.get("KeggPathwaysUrl")));

            int c = 1;
            try{

                String[] elem;
                int count = 1;
                for(String line:fileKGContents){
                    elem = line.split("[\t:]");
                    if(elem.length==4){
                        int keggID = Integer.parseInt(elem[1]);
                        int ncbiid = Integer.parseInt(elem[3]);
                        SQLMgr.insertKeggGene(keggID,ncbiid);
                    }else{
                        System.out.println("Malformed line in kegg gene file");
                    }
                    count ++;
                    c ++;
                }
            }catch(Exception e){
                //todo deal with errors
                e.printStackTrace();
            }

            try{
                String[] elem;
                for(String line:fileKGPContents){
                    elem = line.split("[\t:]");
                    if(elem.length==4){
                        int keggID = Integer.parseInt(elem[1]);
                        String pathwayid = elem[3].substring(3, elem[3].length());
                        SQLMgr.insertKeggGenePathways(keggID,pathwayid);
                    }else{
                        System.out.println("Malformed line in kegg gene file");
                    }
                    c ++;
                }
            }catch(Exception e){
                //todo deal with errors
                e.printStackTrace();
            }


            try{
                String[] elem;
                int count = 1;
                for(String line:fileKPContents){
                    elem = line.split("[\t]");
                    if(elem.length==2){
                        String pathwayid = elem[0].trim();
                        String desc = elem[1].trim();
                        SQLMgr.insertKeggPathway(count,pathwayid,desc);
                    }else{
                        System.out.println("Malformed line in kegg gene file");
                    }
                    count ++;
                    c ++;
                }
            }catch(Exception e){
                //todo deal with errors
                e.printStackTrace();
            }

        }catch(Exception e){
            //todo deal with errors
            e.printStackTrace();
        }

    }

    public EntrezGeneSummary getEntrezGeneSummary(int ID) {

        String defaultServer = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&id=" + ID;

        EntrezGeneSummary summary = null;
        String server = defaultServer;
        try {
            // Connect to the server
            URL u = new URL(server);
            URLConnection uc = u.openConnection();
            HttpURLConnection connection = (HttpURLConnection) uc;
            connection.setDoOutput(false);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.connect();

            // Read the response
            InputStream in = connection.getInputStream();
            summary = readGeneSummaryFromResponse(in);

            in.close();
            connection.disconnect();


        } catch (IOException e) {
            System.err.println(e);
        }
        return summary;
    }

    private EntrezGeneSummary readGeneSummaryFromResponse(InputStream in) throws IOException, StringIndexOutOfBoundsException {

        StringBuffer sb = new StringBuffer();
        //Reader reader = new InputStreamReader(new File("c:test.xml"));
        // int c;
        //while ((c = in.read()) != -1) sb.append((char) c);

        //String document = sb.toString();

        final SAXBuilder builder = new SAXBuilder();
        EntrezGeneSummary summary = null;
        try {
            final Document doc = builder.build(in);
            final Element eSummaryResult = doc.getRootElement();
            final Element DocSum = eSummaryResult.getChild("DocSum");
            List items = DocSum.getChildren("Item");
            Iterator<Element> iter = items.iterator();
            summary = new EntrezGeneSummary();
            ArrayList list = new ArrayList();
            while (iter.hasNext()) {
                Element elem = iter.next();
                String name = elem.getAttributeValue("Name");



                if (name.equalsIgnoreCase("Name")) {
                    String n = elem.getText().trim();
                    summary.setName(n);
                    list.add(n);
                }

                if (name.equalsIgnoreCase("Description")) {
                    String c = elem.getText().trim();
                    summary.setDescription(c);
                }
                if (name.equalsIgnoreCase("Orgname")) {
                    String c = elem.getText().trim();
                    summary.setOrgname(c);
                }

                if (name.equalsIgnoreCase("MapLocation")) {
                    String c = elem.getText().trim();
                    summary.setMapLocation(c);
                }

                if (name.equalsIgnoreCase("Chromosome")) {
                    String c = elem.getText().trim();
                    summary.setChromosome(c);
                }
                if (name.equalsIgnoreCase("OtherAliases")) {
                    String[] s = elem.getTextTrim().split(",");
                    if (s.length > 0) {
                        for (int i = 0; i < s.length; i++) {
                            list.add(s[i].trim());
                        }
                    }
                }

                if (name.equalsIgnoreCase("GenomicInfo")) {
                    List genList = elem.getChildren("Item");
                    Iterator<Element> genIter = genList.iterator();
                    while (genIter.hasNext()) {
                        Element gElem = genIter.next();
                        name = gElem.getAttributeValue("Name");
                        if (name.equalsIgnoreCase("GenomicInfoType")) {
                            List infList = gElem.getChildren("Item");
                            Iterator<Element> infIter = infList.iterator();
                            while (infIter.hasNext()) {
                                Element infElem = infIter.next();
                                name = infElem.getAttributeValue("Name");
                                if (name.equalsIgnoreCase("ChrStart")) {
                                    String c = infElem.getText().trim();
                                    summary.setStart(c);
                                }

                                if (name.equalsIgnoreCase("ChrStop")) {
                                    String c = infElem.getText().trim();
                                    summary.setEnd(c);
                                }
                            }
                        }
                    }
                }


            }
            summary.setAliases(list);
        } catch (Exception e) {
            System.err.println("err getting gene sumary for ");
        }
        return summary;

    }
}
